<template>
  <view class="list-order-wrap">
    <view class="header">
      <!-- tab 切换 -->
      <view class="tab-box">
        <u-tabs
          :list="classOrderList"
          :current="current"
          :fontSize="28"
          :isScroll="false"
          bgColor="#ffffff"
          inactiveColor="#999999"
          @change="handleTabChange"
          :active-item-style="{ color: '#333' }"
          :bar-style="{ background: '#FEDD00', borderRadius: '100rpx' }"
        ></u-tabs>
      </view>
      <view class="tab-box">
        <u-tabs
          :list="fromPlaceList"
          :current="current1"
          :fontSize="28"
          :isScroll="false"
          bgColor="#ffffff"
          inactiveColor="#999999"
          @change="handleToOrderList"
          :active-item-style="{ color: '#333' }"
          :bar-style="{ background: '#FEDD00', borderRadius: '100rpx' }"
        ></u-tabs>
      </view>
    </view>

    <view class="list">
    <!--  <view class="item" v-for="(item, index) in items" :key="index" @tap="handleToDetail(item)"> -->
      <view class="item" v-for="(item, index) in items" :key="index">
        <view class="merber">
          <view class="merber__time" v-if="item.pay_type===1">
            下单时间：{{ item.created_at }}<span class="right" >(货到付款)</span>
          </view>
          <view class="merber__time" v-else-if="item.pay_time==null || item.pay_type==undefined " >
            下单时间：{{ item.created_at }}
          </view>
          <view class="merber__time" v-else >
            支付时间：{{ item.pay_time }}
          </view>
          <view class="status" >
            {{ item.status | statusValueFilter }}
          </view>
        </view>
        <view class="info">
          <div  class="go-box" >
            <div class="go-icon" >发</div>
            <div class="go-address" >
              姓名:{{item.sender_name}}   电话:{{item.mobile}} </br>
              <div v-if="item.order_type === 1" ><span class="right" >{{item.cateTypeCnt}}</span>种商品，共<span class="right" >{{ item.productCnt }}</span>件</div>
            </div>
          </div>
          
          </div>
          <div class="go-box" >
            <div class="go-icon red" >收</div>
            <div class="go-address" >
              {{ item.region }}</br>
              姓名：{{item.buyer_name }} </br> 电话：{{item.buyer_phone}}
            </div>
          </div>
          <!-- 支付金额 -->
          <div class="pay-box" >
            <div v-if="item.order_type === 1" >
              <span class="pay-box__label" >订单号: </span>
              <span class="pay-box__value" >{{ item.order_sn }}</span>
               <text
              class="copy"
              @click="handleCopy(item.order_sn)"
            >
              复制
            </text>
            </div>
             <div v-if="item.order_type === 2" >
              <span class="pay-box__label" >取件码: </span>
              <span class="pay-box__value" >{{ item.pick_up_code }}</span>
            </div>
            <div v-if="item.order_type === 2" >
              <span class="pay-box__label" >取件人: </span>
              <span class="pay-box__value" >{{ item.pick_up_name}}</span>
              <span class="pay-box__value" >-</span>
              <span class="pay-box__value" >{{ item.pick_up_phone}}</span>
            </div>
            <div
            v-if="item.status === 1"
            class="receive-btn active-btn" @click.stop="handleToReceive(item)" >取货</div>
            <div style="display: flex;" v-if="item.status === 2" >
              <div
              class="receive-btn active-btn"
              style="margin-right: 12rpx;"
              @click.stop="handleToComplate(item)"
               >送达</div>
             <!-- <div
              style="background-color: #EEEEEE;"
              @click.stop="handleCancel(item)"
              class="receive-btn active-btn" >取消</div> -->
            </div>

          </div>
        </view>
      </view>
      <view class="full-green" v-if="!isEmpty">
        <load-more :status="loadingStatus"></load-more>
      </view>
      <view v-else>
        <u-empty description="暂无订单～"></u-empty>
      </view>
    </view>


  </view>
</template>

<script>
import loadMore from '@/components/load-more.vue';
import uEmpty from '@/basic-components/u-empty/index.vue';
import uTabs from '@/basic-components/u-tabs/index.vue';
import countDown from '@/basic-components/u-count-down/index.vue';
import { momentDate ,copyFunc} from '@/tool';


import moreLoadMixins from '@/common/load-more';

import { LIST_RUN, LIST_RUN_GROUP,CANCEL_RUN, FINISH_RUN,TAKE_RUN, ORDER_LIST } from '@/api';

export default {
  components: {
    loadMore,
    uEmpty,
    uTabs,
    countDown
  },
  mixins: [moreLoadMixins],
  data() {
    return {
      // tab切换
      current: 0,
      current1:0,
      fromIndex:0,
      orderType:0,
      classOrderList: [{
        name: '待取货'
      },{
        name: '待收货'
      },{
        name: '已完成'
      }
      //,{
       // name: '已取消'
      //}
      ],
      fromPlaceList:[]

    };
  },
  async onLoad(option){
    const {orderType}=option;
    this.orderType=orderType;
  },
  async onShow(options) {
    if(options && options.current) {
      this.items = [];
      this.current = +options.current;
    }
    // 列表信息
    this.resetInit();
  },
  async onPullDownRefresh() {
    // 初始化
    await this.resetInit();
    uni.stopPullDownRefresh();
  },
  filters: {
    statusValueFilter(val) {
      const statusObj = {
        1: '待取货',
        2: '待收货',
        3: '已完成',
        4: '已取消',
      }

      return statusObj[val]
    }
  },
  methods: {
    handleToDetail(item) {
      this.$navigate({
        page: 'runDetail',
        params: {
          item:  JSON.stringify(item)
        },
      });
    },
    handleTabChange(index) {
      if(this.current === index) {
        return
      }
      this.current = index;
      this.fromPlaceList=[];
      this.current1=0;
      this.fromIndex=0;
      this.resetInit();
    },
    endTime() {
      this.resetInit();
    },
    async initData() {
      // 列表搜索
      const params = {};
      params.page = this.pages.currentPage;
      params.per_page = this.pages.perPage;
      params.order_type = this.orderType;
      // this.fromPlaceList=[];
        const statusInt = {
           0: 1,
           1: 2,
           2: 3,
           3: 4
         }
      params.status = statusInt[this.current];
      let  api = LIST_RUN_GROUP;
      this.$http.get(api, params).then(res => {
        const { data, name, cnt } = res;
          if (data && data.length) {
            if(this.fromPlaceList.length<=0){
              data.forEach(item => {
                let place={};
                place.id=item.object_id;
                place.name=item.object_name;
                place.cnt=item.order_count;
                this.fromPlaceList.push(place);
              });
            }
            console.log('initData------',this.current1);
            this.current1=this.fromIndex;
            this.getList(this.fromPlaceList[this.current1]);
      }
    }); 
    },
    handleToOrderList(eIndex){
      if(this.current1 === eIndex) {
        return
      }
      console.log('handleToOrderList----',eIndex);
      this.resetInit();
      this.fromIndex=eIndex;
      // this.getList(this.fromPlaceList[e]);
    },
    getList(object){
      const statusInt = {
           0: 1,
           1: 2,
           2: 3,
           3: 4
         }
        // 列表搜索
      const params = {};
      params.status = statusInt[this.current];
      params.page = this.pages.currentPage;
      params.per_page = this.pages.perPage;
      params.order_type = this.orderType;
      if(this.orderType==1){
        params.shopId=object.id;
      }else{
        params.branchId=object.id;
      }
      
      let api = LIST_RUN;
      return this.$http.get(api, params).then(res => {
        const { data, last_page, current_page, total } = res;

        if (data && data.length) {

          data.forEach(item => {
            item.productCnt=0;
            item.created_at = momentDate(item.created_at);
            if(item.start_time) {
              item.start_time = momentDate(item.start_time);
            }
            if(item.end_time) {
              item.end_time = momentDate(item.end_time);
            }
            if(item.updated_at) {
              item.updated_at = momentDate(item.updated_at);
            }
            item.orderCount=object.order_count;
            if(this.orderType==1){
              item.cateTypeCnt=item.item_list.length;
              item.item_list.forEach(pro=>{
                  item.productCnt=(item.productCnt+ parseInt(pro.item_cnt));
              });
            }
            

          });

          this.items = this.items.concat(data);
          this.pages.currentPage=current_page+1;
        }
        return {
          perPage: this.pages.perPage,
          currentPage: this.pages.currentPage,
          hasNext: !last_page === current_page,
          empty: current_page === 1 && total === 0,
        };
      });
    },

    /**
     * 接单
     */
    handleToReceive(item) {
      uni.showToast({
        title: '请求中...',
        mask: true,
        icon: 'loading',
        duration: 300000,
      });
      this.$http.put(TAKE_RUN, {
        id: item.id
      })
      .then(() => {
        uni.showToast({
          title: '取货成功',
          icon: 'success',
        });
        this.resetInit();
        setTimeout(() => {
           uni.hideToast();
        }, 1000)
      })
      .catch(() => {

        uni.hideToast();
      })
    },
    /**
     * 送达
     */
    handleToComplate(item) {
      uni.showModal({
        title: '温馨提示',
        content: `确认送达?`,
        success: res => {
          if (res.confirm) {

             this.complateOrder(item)
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });

    },
    complateOrder(item) {
      this.$http.put(FINISH_RUN, {
        id: item.id
      },{
        showLoading: true
      })
      .then(() => {
        uni.showToast({
          title: '送达成功',
          icon: 'success',
        });
        this.resetInit();
      })
    },
    handleCancel(item) {
      uni.showModal({
        title: '温馨提示',
        content: `确定取消?`,
        success: res => {
          if (res.confirm) {

             this.cancelOrder(item)
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    },
     handleCopy(orderId) {
        // 订单号复制
        copyFunc(String(orderId));
      },
    cancelOrder(item) {
      this.$http.put(CANCEL_RUN, {
        id: item.id
      },{
        showLoading: true
      })
      .then(() => {
        uni.showToast({
          title: '取消成功',
          icon: 'success',
        });
        this.resetInit();
      })

    }
  },
};
</script>

<style lang="less">
.list-order-wrap {
  padding-bottom: 150rpx;
  padding-bottom: calc(150rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(150rpx + env(safe-area-inset-bottom));
  .header {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 118rpx;
    padding-top: 24rpx;
    background: #fff;
  }
  .tab-box{
    width: 100%;
    background-color: #FFFFFF;
  }
  .right{
    text-align:right;
    font-size:18px;
    color:red;
    padding:5px;
  }
  .list {
    display: flex;
    flex-direction: column;
    padding-top: 176rpx;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
    .item {
      position: relative;
      width: 710rpx;
      padding: 24rpx;
      padding-bottom: 0;
      margin: auto;
      margin-bottom: 20rpx;
      background-color: #ffffff;
      border-radius: 16rpx;
      .merber {
        display: flex;
        align-items: center;
        justify-content: space-between;
        &__time{
          font-size: 28rpx;
          color: #999999;
        }
        .status{
          font-size: 28rpx;
          flex-shrink: 0;
          margin-right: 10rpx;
          color: #FF6034;
        }
      }
      .info {
        padding: 20rpx 0;
        .go-box{
          display: flex;
          align-items: center;
          margin-bottom: 20rpx;
          .go-icon{
            width: 66rpx;
            height: 66rpx;
            margin-right: 10px;
            text-align: center;
            line-height: 66rpx;
            font-size: 28rpx;
            flex-shrink: 0;
            color: #FFFFFF;
            border-radius: 50%;
            background-color: #000000;
            &.red{
              background-color: red;
            }
          }

        }
      }
    }
  }
  .pay-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20rpx;
    border-top: 1px solid #EEEEEE;
    &__label{
      font-size: 28rpx;
      font-weight: bold;
      margin-right: 20rpx;
    }
    &__value{
      color: red;
      font-weight: bold;
    }
    .receive-btn{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100rpx;
      height: 44rpx;
      font-size: 24rpx;
      color: #FFFFFF;
      border-radius: 8rpx;
      background-color: red;
    }
  }
  .copy{
    margin-left: 30rpx;
    color: red;
  }
  .btn-box {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 136rpx;
    .cancel-btn {
      width: 710rpx;
      height: 92rpx;
      font-size: 32rpx;
      background-color: #fedd00;
    }
  }
}
</style>
